package virtualstock.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import virtualstock.exception.InvalidParameterException;
import virtualstock.request.PlayerController;
import virtualstock.util.PlayerDetails;

/**
 * Servlet implementation class CreatePlayerServlet
 */
public class CreatePlayerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private PlayerController playerController; 
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreatePlayerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	
    	String email = (String) request.getParameter("email");
    	String password = (String) request.getParameter("password");
    	String firstName = (String) request.getParameter("firstname");
    	String lastName = (String) request.getParameter("lastname");
    	
    	try {
    		PlayerDetails details = new PlayerDetails(email, password, firstName, lastName);
    		Long playerID = playerController.createPlayer(details);
        	details.setPlayerID(playerID);
		} catch (InvalidParameterException e) {
			out.print("InvalidParameterException");
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("ListPlayerServlet").forward(request, response);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
